package com.hwtx.form.domain;

import cn.hutool.extra.spring.SpringUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.hwtx.form.annotation.FormType;
import com.hwtx.form.domain.def.FormDef;
import com.hwtx.form.domain.service.FormService;
import com.hwtx.form.domain.vo.FormListVo;
import com.hwtx.form.dto.FormListQuery;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.Paging;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@Service
public class FormListService {

    @Resource
    private FormService formService;

    private static final Cache<String, FormSearchExt> searchExtCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.DAYS).recordStats().build();

    @PostConstruct
    public void setup() {
        Map<String, FormSearchExt> searchExts = SpringUtil.getApplicationContext().getBeansOfType(FormSearchExt.class);
        searchExts.values().forEach(searchExt -> {
            FormType formType = searchExt.getClass().getAnnotation(FormType.class);
            if (formType != null) {
                Stream.of(formType.value()).forEach(id -> {
                    FormSearchExt formSearchExt = searchExtCache.getIfPresent(id);
                    if (formSearchExt != null) {
                        throw new BusinessException(MessageFormat.format("表单查询扩展已经存在，formId = {0}", id));
                    } else {
                        searchExtCache.put(id, searchExt);
                    }
                });
            }
        });
    }

    public FormListVo<?> list(FormListQuery formListQuery) throws Exception {
        FormDef formDef = formService.getFormDef(formListQuery.getFormId());
        if (formDef == null) {
            throw new RuntimeException("表单标识不正确");
        }
        return formService.getFormList(formListQuery);
    }

    public Paging<?> page(FormListQuery formListQuery) throws Exception {
        FormDef formDef = formService.getFormDef(formListQuery.getFormId());
        if (formDef == null) {
            throw new RuntimeException("表单标识不正确");
        }
        return formService.page(formListQuery);
    }
}
